package com.hjxr.quota.util;

import org.apache.commons.io.IOUtils;

import java.io.*;

/**
 * @author ma
 * @date 2020/9/11 - 14:41
 **/
public class CleanBom {

    /**
     * 清除bom编码
     *
     * @param file
     */
    public static void cleanBom(File file) {

        File tempFile = new File(file.getAbsolutePath() + ".tmp");

        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream(tempFile);
            fis = new FileInputStream(file);
            fis.read(new byte[3]);//读取前3个byte
            IOUtils.copy(fis, fos);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(fis);
        }

        if (!file.delete()) {
            System.out.println("Could not delete file");
        }

        if (!tempFile.renameTo(file)) {
            System.out.println("Could not rename file");
        }

        System.out.println(file.getAbsolutePath() + ">>clean bom");

    }



    /**
     * 判断是否为bom编码文件
     *
     * @param file
     * @return
     */
    public static boolean isBomFile(File file) {
        boolean isBom = false;
        FileInputStream fileIS = null;
        try {
            fileIS = new FileInputStream(file);

            byte[] bomBytes = new byte[3];
            fileIS.read(bomBytes);

            //EF BB BF
            if (bomBytes[0] == -17 && bomBytes[1] == -69 && bomBytes[2] == -65) {
                isBom = true;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fileIS);

        }
        return isBom;
    }
}
